package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.ndp.ec.core.FeedBuilderService;
import com.ndp.ec.core.api.EcTemplateCoreServcice;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.enums.ec.EcTemplateMaterielCreatedStatus;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.exception.S3Exception;
import com.ndp.fb.mongo.api.FeedMongoService;
import com.ndp.fb.mongo.model.Feed;
import com.ndp.fb.rdb.api.EcElementCategoryRdbService;
import com.ndp.fb.rdb.api.EcElementStyleColorTypeRdbService;
import com.ndp.fb.rdb.api.EcMaterielCategoryRdbService;
import com.ndp.fb.rdb.api.EcMaterielElementsRdbService;
import com.ndp.fb.rdb.api.EcMaterielTagRdbService;
import com.ndp.fb.rdb.api.EcProductLogoRdbService;
import com.ndp.fb.rdb.api.EcTemplateElementRdbService;
import com.ndp.fb.rdb.api.EcTemplateMaterielRdbService;
import com.ndp.fb.rdb.api.EcTemplateRdbService;
import com.ndp.fb.rdb.api.FeedRdbService;
import com.ndp.fb.rdb.api.ProductCatalogRdbService;
import com.ndp.fb.rdb.model.EcElementCategory;
import com.ndp.fb.rdb.model.EcMaterielCategory;
import com.ndp.fb.rdb.model.EcMaterielCategorys;
import com.ndp.fb.rdb.model.EcMaterielElements;
import com.ndp.fb.rdb.model.EcMaterielElementsExt;
import com.ndp.fb.rdb.model.EcMaterielTag;
import com.ndp.fb.rdb.model.EcTemplate;
import com.ndp.fb.rdb.model.EcTemplateElement;
import com.ndp.fb.rdb.model.EcTemplateMateriel;
import com.ndp.fb.rdb.model.EcTemplateMaterielExt;
import com.ndp.fb.rdb.model.EcTemplateMaterielFeedExt;
import com.ndp.fb.rdb.model.FeedWe;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ectemplate.EcElementStyleColorTypeShowResult;
import com.ndp.fb.rdb.model.ectemplate.EcProductLogo;
import com.ndp.fb.rdb.model.ectemplate.EcTemplateElementShowResult;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.storage.StorageService;
import com.ndp.fb.util.FileUtil;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.ThreadPool;
import com.ndp.fb.walle.business.EcTemplateMaterielService;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.AdvancedParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.EcBuildCreativeParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.EcTempMateSaveParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.TemplateElementVo;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by hexin on 2016/5/20.
 */
@Component
public class EcTemplateMaterielServiceImpl implements EcTemplateMaterielService {

    @Reference
    EcTemplateMaterielRdbService ecTemplateMaterielRdbService;

    @Reference
    private EcMaterielTagRdbService ecMaterielTagRdbService;
    @Reference
    private EcMaterielElementsRdbService ecMaterielElementsRdbService;

    @Reference
    private FeedRdbService feedRdbService;
    @Reference
    private EcTemplateCoreServcice ecTemplateCoreServcice;
    @Autowired
    private StorageService storageService;

    @Reference
    EcMaterielCategoryRdbService ecMaterielCategoryRdbService;

    @Reference
    EcElementCategoryRdbService ecElementCategoryRdbService;

    @Reference
    private ProductCatalogRdbService productCatalogRdbService;

    private final Logger logger = LoggerFactory.getLogger(EcTemplateMaterielServiceImpl.class);

    @Autowired
    private RedisClient redisClient;

    @Reference
    FeedBuilderService feedBuilderService;

    @Reference
    EcTemplateRdbService ecTemplateRdbService;

    @Reference
    EcTemplateElementRdbService ecTemplateElementRdbService;

    @Reference
    FeedMongoService feedMongoService;

    @Reference
    private EcProductLogoRdbService ecProductLogoRdbService;

    @Reference
    private EcElementStyleColorTypeRdbService EcElementStyleColorTypeRdbService;

    @Override
    public EcTemplateMaterielExt findext(Long id) {
        return ecTemplateMaterielRdbService.findExtById(id);
    }

    @Override
    public EcTemplateMateriel findById(Long id) {
        return ecTemplateMaterielRdbService.findEcTemplateMaterielById(id);
    }

    @Override
    public Integer getprogress(Long id) {
        EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(id);
        Integer process = 0;
        //完成
        process = getMaterielProgress(ecTemplateMateriel);
        return process;
    }

    private Integer getMaterielProgress(EcTemplateMateriel ecTemplateMateriel) {
        Integer process;
        if (ecTemplateMateriel.getCreatedStatus() == EcTemplateMaterielCreatedStatus.CreateEnd.getType()) {
            process = 100;
        } else if (ecTemplateMateriel.getCreatedStatus() == EcTemplateMaterielCreatedStatus.CreateIng.getType()) {
            String createRedisKey = ecTemplateMateriel.getId() + CommonConstants.MATERIEL_PROCESS_KEY; //当前生成个数
            Long createdImgNo = (Long) redisClient.get(createRedisKey);
            createdImgNo = createdImgNo == null ? 0 : createdImgNo;
            Integer productCount = ecTemplateMateriel.getProductCount();
            //产品数量为0
            if (productCount == null || productCount == 0) {
                process = 0;
            }
            //如果生成数量大于产品数量
            else if (createdImgNo != null && createdImgNo >= productCount) {
                process = 100;
            }
            // 正常情况
            else {
                float num = ((float) createdImgNo / productCount) * 100;
                process = new BigDecimal(num).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            }
        } else {
            process = 0;
        }
        return process;
    }

    @Override
    public Pager<Map> findPager(Integer feedId, User user, String name, Long tagId, String type, List<String> creativeStatus, List<Map<String, List<String>>> categoryList, Integer firstResult, Integer sizeNo, String order) {
        Pager<EcTemplateMateriel> pager = null;
        if ("1".endsWith(type)) { //按照名称查询& 默认查询
            pager = ecTemplateMaterielRdbService.findPagerByName(feedId, user, name, creativeStatus, categoryList, firstResult,
                    sizeNo, order);
        }
        // 没有选择标签
        else if (tagId == null || tagId.intValue() == 0 || tagId.intValue() == -1) {
            pager = ecTemplateMaterielRdbService.findPagerByName(feedId, user, name, creativeStatus, categoryList, firstResult,
                    sizeNo, order);
        }
        //按照标签查询
        else {
            pager = ecTemplateMaterielRdbService.findPagerByTag(feedId, user, tagId, creativeStatus, categoryList, firstResult,
                    sizeNo, order);
        }
        Pager<Map> resultPager = new Pager<>();
        resultPager.setPageIndex(pager.getPageIndex());
        resultPager.setPageSize(pager.getPageSize());
        resultPager.setTotalSize(pager.getTotalSize());

        List<Map> xx = new ArrayList<>();
        for (EcTemplateMateriel ecTemplateMateriel : pager.getResultList()) {
            Map map = new HashMap<>();

            map.put("materiel", ecTemplateMateriel);
            Long id = ecTemplateMateriel.getId();
            if (EcTemplateMaterielCreatedStatus.CreateEnd.getType() == ecTemplateMateriel.getCreatedStatus()
                    || EcTemplateMaterielCreatedStatus.Error.getType() == ecTemplateMateriel.getCreatedStatus()) {
                EcTemplateMaterielExt ecTemplateMaterielExt = ecTemplateMaterielRdbService.findExtById(id);
                map.put("ext", ecTemplateMaterielExt);
            } else {
                EcTemplateMaterielExt ecTemplateMaterielExt = new EcTemplateMaterielExt();
                ecTemplateMaterielExt.setCnt(0);
                ecTemplateMaterielExt.setRunning(0);
                ecTemplateMaterielExt.setPaused(0);
                ecTemplateMaterielExt.setDeleted(0);
                map.put("ext", ecTemplateMaterielExt);
            }
            map.put("process", getMaterielProgress(ecTemplateMateriel));
            xx.add(map);
        }

        resultPager.setResultList(xx);
        return resultPager;

    }

    @Override
    public Map viewMore(Long id) {
        Map<String, Object> map = new HashMap<>();
        EcTemplateMaterielFeedExt ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielFeedExtById(id);
        if (ecTemplateMateriel != null) {
            Long feedId = ecTemplateMateriel.getFeedId();
            List<Feed> list = feedMongoService.sampleByNewFeed(feedId, id, 50);
            map.put("feedList", list);
        } else {
            logger.error("viewMore ecTemplateMateriel not found id >>>>" + id);
        }

        List<EcMaterielTag> tags = ecMaterielTagRdbService.findTagsByMaterielId(id);
        map.put("tags", tags);
        map.put("materiel", ecTemplateMateriel);
        return map;
    }

    @Override
    public List<EcMaterielTag> queryTags(User user, String q) {
        Long orgId = user.getOrgId();
        return ecMaterielTagRdbService.findByTagNameLike(orgId, q);
    }

    @Override
    public void delete(User user, Long id) {
        Long orgId = user.getOrgId();
        ecTemplateMaterielRdbService.delete(orgId, id);
    }

    @Override
    public Long save(EcTempMateSaveParam param, User user) throws CheckedException {

        // 查找ecTemplate
        EcTemplate ecTemplate = getEcTemplateFillColor(param);

        if ("new".equalsIgnoreCase(param.getSaveType())) {
            // 新建模板样式
            return saveNew(param, user, ecTemplate);
        } else {
            // 更新模板样式
            return updateMaterial(param, user, ecTemplate);
        }
    }

    /**
     * @param param
     * @return
     */
    private EcTemplate getEcTemplateFillColor(EcTempMateSaveParam param) {
        EcTemplate ecTemplate = ecTemplateRdbService.findById(param.getTemplateId());
        logger.info("CreativeTemplateBuildServiceImpl 准备使用模板 templateId>>>" + ecTemplate.getId());
        return ecTemplate;
    }

    private Long updateMaterial(EcTempMateSaveParam param, User user, EcTemplate ecTemplate) throws CheckedException {
        String materialCode = ecTemplate.getTemplateCode();
        Long ecTemplateMaterielId = param.getEcTemplateMaterielId();

        //name
        String name = param.getName();
        Long templateId = param.getTemplateId();
        ecTemplateMaterielRdbService.updateNameAndTemplateId(name, templateId, ecTemplateMaterielId);

        //tags
        saveOrUpdateMaterielTags(param, user, ecTemplateMaterielId);


        boolean changeProperty = false;  // 元素内容是否有修改  填充值、背景颜色、字体颜色

        //如果模板存在 颜色背景在处理
        String templateBgStyle = null;
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(param.getMainBgColor())) {
            templateBgStyle = "1" + param.getMainBgColor();
            logger.info("getMainBackgroudColor isnot null templateId>>>" + param.getMainBgColor());
        }

        if (org.apache.commons.lang3.StringUtils.isNoneBlank(param.getJoinBgColor())) {
            templateBgStyle = "1" + param.getJoinBgColor();
            logger.info("getJoinBackgroudColor isnot null templateId>>>" + param.getJoinBgColor());
        }

        //重新生成EcTemplate完全编码

        EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(ecTemplateMaterielId);
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(templateBgStyle)
                && org.apache.commons.lang3.StringUtils.isNoneBlank(ecTemplateMateriel.getTemplateCode())
                && !ecTemplateMateriel.getTemplateCode().contains(templateBgStyle)) {
            String templateName = ecTemplate.getTemplateName();
            String[] split = templateName.split("_");
            // 构造最新的全编码
            if (split.length > 5 && (split[4].equals("BG02") || split[4].equals("BG01"))
                    && split[5].startsWith("1") && org.apache.commons.lang3.StringUtils.isNoneBlank(ecTemplate.getTemplateBgStyle())) {
                split[5] = templateBgStyle;
                templateName = Joiner.on("_").join(split);
                ecTemplate.setTemplateBgStyle(templateBgStyle);
                logger.info("CreativeTemplateBuildServiceImpl 模板背景修改 templateName>>>" + ecTemplate.getTemplateName() + ";templateBgStyle>>>" + templateBgStyle + ";"
                        + ";newtemplateName>>>" + templateName);
                ecTemplate.setTemplateName(templateName);
                ecTemplateMaterielRdbService.updateTemplateCode(templateName, ecTemplateMaterielId);
                changeProperty = true;
            }
        }

        List<EcMaterielElements> srcDbElement = ecMaterielElementsRdbService.findByMaterielId(ecTemplateMaterielId);
        // save ecTemplateElements
        List<EcMaterielElements> stillStayElementList = new ArrayList<>(); // 没有更换掉的元素
        List<EcMaterielElements> ecTemplateElements = new ArrayList<>();
        for (TemplateElementVo templateElementVo : param.getElements()) {

            boolean isExist = false;

            for (EcMaterielElements ecMaterielElements : srcDbElement) {

                //没有更换元素
                if (ecMaterielElements.getElementCode().equals(templateElementVo.getElementCode())) {

                    materialCode = materialCode + "_" + templateElementVo.getElementCode() + "_";

                    //填充值修改
                    if (!Objects.equals(ecMaterielElements.getFillValue(), templateElementVo.getFillValue())) {
                        ecMaterielElements.setFillValue(templateElementVo.getFillValue());
                        ecTemplateElementRdbService.updateFillValue(templateElementVo.getFillValue(), ecMaterielElements.getId());
                        logger.info(ecMaterielElements.getElementCode() + " 填充值修" + ecMaterielElements.getFillValue() + " 修改后" + templateElementVo.getFillValue());
                        changeProperty = true;
                    }

                    //判断颜色是否修改
                    boolean isChangeColor = false;
                    String backgroundColor = templateElementVo.getBackgroundColor();
                    String wordColor = templateElementVo.getWordColor();
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(backgroundColor)
                            || org.apache.commons.lang3.StringUtils.isNoneBlank(backgroundColor)) {
                        String context = ecMaterielElements.getElementContext();
                        JSONObject contextJ = JSON.parseObject(context);
                        String dbBackgroundColor = contextJ.getString("backgroundColor");
                        String dbWordColor = contextJ.getString("color");

                        //修改了背景
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(backgroundColor)
                                && (dbBackgroundColor == null || !dbBackgroundColor.equals("#" + backgroundColor))) {
                            contextJ.put("backgroundColor", "#" + backgroundColor);
                            isChangeColor = true;
                        }

                        //修改了字体
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(wordColor)
                                && (dbWordColor == null || !dbWordColor.equals("#" + wordColor))) {
                            contextJ.put("color", "#" + wordColor);
                            isChangeColor = true;
                        }

                        if (isChangeColor) {
                            changeProperty = true;
                            String tempContext = contextJ.toJSONString();
                            ecMaterielElements.setElementContext(tempContext);
                            ecTemplateElementRdbService.updateContext(tempContext, ecMaterielElements.getId());
                        }
                    }

                    ecTemplateElements.add(ecMaterielElements);
                    stillStayElementList.add(ecMaterielElements);
                    isExist = true;
                }
            }

            if (isExist) {
                continue;
            } else {
                EcTemplateElement dbElement = getEcTemplateElement(param.getFeedId(), ecTemplate, templateElementVo);
                materialCode = materialCode + "_" + dbElement.getElementCode() + "_";
                EcMaterielElements eme = getEcMaterielElements(ecTemplateMaterielId, user, templateElementVo, dbElement);
                ecTemplateElements.add(eme);
                ecMaterielElementsRdbService.save(eme);
            }
        }

        //删除多余的 原来 A B   现在 B C  需要删除 A
        if (stillStayElementList.size() != 2 || changeProperty) {
            logger.info("元素或者 填充值改变，需要重新生成");
            //更新后置字段
            String desThumbnail = getThumbnailPath(ecTemplateMaterielId, param.getThumbnail());
            String html = ecTemplateCoreServcice.createHtml(ecTemplate, ecTemplateElements, 1);
            ecTemplateMaterielRdbService.updateMaterielCodeAndThumbnailAndMaterielContext(materialCode, desThumbnail, html, ecTemplateMaterielId);

            for (EcMaterielElements ecMaterielElements : srcDbElement) {
                // 本次选择的
                boolean isExist = false;
                for (EcMaterielElements materielElements : stillStayElementList) {
                    if (ecMaterielElements.getParentCode().equals(materielElements.getParentCode())) {
                        isExist = true;
                    }
                }

                if (!isExist) {
                    ecMaterielElementsRdbService.deleteElements(ecMaterielElements.getId());
                }
            }
            //调用生成
            feedBuilderService.buildFeedSyncNotMq(param.getFeedId(), ecTemplateMaterielId, true);
        } else {
            //没有更换元素
            logger.info("元素没有改变，不用重新生成新图片");
        }

        //删除所有目标
        ecMaterielCategoryRdbService.deleteAllByEcTemplateMaterielId(ecTemplateMaterielId);
        saveEcMaterielCategory(param, materialCode, ecTemplateMaterielId);
        return ecTemplateMaterielId;
    }


    @Override
    public boolean reBuild(Long id) {
        EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(id);
        feedBuilderService.buildFeedSyncNotMq(ecTemplateMateriel.getFeedId(), id, true);
        return false;
    }

    private Long saveNew(EcTempMateSaveParam param, User user, EcTemplate ecTemplate) throws CheckedException {

        // check: name uniq in org
        EcTemplateMateriel byNameAndOrgId = ecTemplateMaterielRdbService.findByNameAndOrgId(param.getName(), user.getOrgId());
        if (byNameAndOrgId != null) {
            throw new CheckedException(ErrorType.TemplateNameExists_ERROR);
        }


        // save TemplateMaterie
        FeedWe weFeed = feedRdbService.findFeedWeById(param.getFeedId());
        EcTemplateMateriel o = getEcTemplateMateriel(param, user, ecTemplate, weFeed);
        Long finalEcTemplateMaterielId = ecTemplateMaterielRdbService.save(o);

        //tags
        saveNewMaterielTags(param, user, finalEcTemplateMaterielId);

        String materialCode = ecTemplate.getTemplateCode(); //
        // save ecTemplateElements
        List<EcMaterielElements> ecTemplateElements = new ArrayList<>();
        for (TemplateElementVo templateElementVo : param.getElements()) {
            EcTemplateElement dbElement = getEcTemplateElement(param.getFeedId(), ecTemplate, templateElementVo);

            materialCode = materialCode + "_" + dbElement.getElementCode();
            EcMaterielElements eme = getEcMaterielElements(finalEcTemplateMaterielId, user, templateElementVo, dbElement);
            ecMaterielElementsRdbService.save(eme);
            ecTemplateElements.add(eme);
        }

        //更新后置字段
        String desThumbnail = getThumbnailPath(finalEcTemplateMaterielId, param.getThumbnail());
        String html = ecTemplateCoreServcice.createHtml(ecTemplate, ecTemplateElements, 1);
        ecTemplateMaterielRdbService.updateMaterielCodeAndThumbnailAndMaterielContext(materialCode, desThumbnail, html, finalEcTemplateMaterielId);

        //调用生成
        ThreadPool.execute(() -> {
            feedBuilderService.buildFeedSyncNotMq(param.getFeedId(), finalEcTemplateMaterielId, true);
        });

        saveEcMaterielCategory(param, materialCode, finalEcTemplateMaterielId);
        return finalEcTemplateMaterielId;
    }

    /**
     * 保存tags
     *
     * @param param
     * @param user
     * @param finalEcTemplateMaterielId
     */
    private void saveNewMaterielTags(EcTempMateSaveParam param, User user, Long finalEcTemplateMaterielId) {
        if (param.getTags() != null && param.getTags().size() > 0) {
            param.getTags().forEach(t -> {
                EcMaterielTag byName = ecMaterielTagRdbService.findByOrgIdTagName(user.getOrgId(), t);
                Long tagId;
                if (byName != null) {
                    tagId = byName.getId();
                } else {
                    EcMaterielTag newTag = getEcMaterielTag(user, t);
                    tagId = ecMaterielTagRdbService.save(newTag);
                }
                //保存对应关系
                ecMaterielTagRdbService.saveRelation(finalEcTemplateMaterielId, tagId);
            });
        }
    }

    private void saveOrUpdateMaterielTags(EcTempMateSaveParam param, User user, Long ecTemplateMaterielId) {
        if (param.getTags() != null && param.getTags().size() > 0) {
            List<EcMaterielTag> tags = ecMaterielTagRdbService.findTagsByMaterielId(ecTemplateMaterielId);
            param.getTags().forEach(t -> {
                boolean isExist = false;
                for (EcMaterielTag tag : tags) {
                    if (tag.getTagName().equals(t)) {
                        isExist = true;
                    }
                }
                if (!isExist) {
                    EcMaterielTag byName = ecMaterielTagRdbService.findByOrgIdTagName(user.getOrgId(), t);
                    Long tagId;
                    if (byName != null) {
                        tagId = byName.getId();
                    } else {
                        EcMaterielTag newTag = getEcMaterielTag(user, t);
                        tagId = ecMaterielTagRdbService.save(newTag);
                    }
                    //保存对应关系
                    ecMaterielTagRdbService.saveRelation(ecTemplateMaterielId, tagId);
                }
            });
        }
    }

    /**
     * 根据参数 查找元素
     *
     * @param feedId
     * @param ecTemplate
     * @param templateElementVo
     * @return
     */
    private EcTemplateElement getEcTemplateElement(Long feedId, EcTemplate ecTemplate, TemplateElementVo templateElementVo) {
        EcTemplateElement dbElement = null;

        //按照id进行查询
        if (templateElementVo.getTemplateElementId() != null && templateElementVo.getTemplateElementId() > 0) {
            dbElement = ecTemplateElementRdbService.findById(templateElementVo.getTemplateElementId());
        }

        // 按照模板去查询 ,获取最小风格那个
        else {
            dbElement = ecTemplateElementRdbService.findByParentCodeAndMajor(feedId, ecTemplate.getId(), templateElementVo.getParentCode(), templateElementVo.getMajor());
        }
        return dbElement;
    }

    /**
     * 保存目标
     *
     * @param param
     * @param materialCode
     * @param finalEcTemplateMaterielId
     */
    private void saveEcMaterielCategory(EcTempMateSaveParam param, String materialCode, Long finalEcTemplateMaterielId) throws CheckedException {
        //处理options
        String options = param.getOptions();
        JSONObject jsonObject = JSONObject.parseObject(options);
        Set<String> strings = jsonObject.keySet();

        String creativeType = null;
        List<EcMaterielCategorys> cids = new ArrayList<>();
        for (String string : strings) {
            JSONArray jsonArray = jsonObject.getJSONArray(string);
            for (Object o1 : jsonArray) {
                JSONObject el = (JSONObject) o1;
                if (el.getBoolean("checked")) {
                    String categoryType = el.getString("categoryType");
                    Long id = el.getLong("id");
                    Long pid = el.getLong("pid");
                    if ("festival".equals(categoryType)) {
                        continue;
                    }
                    if ("creativeType".equals(string)) {
                        creativeType = categoryType;
                    }
                    EcMaterielCategorys ec = new EcMaterielCategorys();
                    ec.setCategoryId(id);
                    ec.setEcTemplateMaterielId(finalEcTemplateMaterielId);
                    ec.setParentCategoryId(pid);
                    cids.add(ec);
                }
            }
        }

        EcMaterielCategorys ec = new EcMaterielCategorys();
        ec.setEcTemplateMaterielId(finalEcTemplateMaterielId);

        // CA 轮播广告 LA 链接广告
        //CA：全局/左右/上下
        //LA：全局/左中右/上下
        // like CAA CAB CAC or LAA LAB LAC
        String codeCategoryType = creativeType + materialCode.substring(0, 1).toUpperCase();
        EcMaterielCategory ecMaterielCategory = ecMaterielCategoryRdbService.findByCategoryType(codeCategoryType);
        if (ecMaterielCategory == null) {
            logger.error("模板编码错误>>>" + materialCode);
            throw new CheckedException(ErrorType.TemplateCode_ERROR);
        } else {
            ec.setParentCategoryId(ecMaterielCategory.getPid());
            ec.setCategoryId(ecMaterielCategory.getId());
        }
        cids.add(ec);
        //保存目标关系
        ecMaterielCategoryRdbService.save(finalEcTemplateMaterielId, cids);
    }

    private String getThumbnailPath(Long tempMateId, String thumbnail) throws CheckedException {

        try {
            String src = thumbnail.replace(storageService.getHttpUrl(""), "");
            File s3File = storageService.getS3File(src);
            String s = storageService.storeMaterialStyleAsPublic(tempMateId, s3File);
            String httpUrl = storageService.getHttpUrl(s);
            FileUtil.deleteQuietly(s3File);
            return httpUrl;
        } catch (IOException | S3Exception e) {
            throw new CheckedException("缩略图异常。");
        }


    }

    private EcMaterielTag getEcMaterielTag(User user, String t) {
        EcMaterielTag newTag = new EcMaterielTag();
        newTag.setOrgId(user.getOrgId());
        newTag.setTagName(t);
        newTag.setUserId(user.getTicket());
        newTag.setIsDelete(0);
        newTag.setCreateTime(new Date());
        return newTag;
    }

    private EcMaterielElements getEcMaterielElements(Long TemplateMaterielId, User user, TemplateElementVo e, EcTemplateElement dbElement) {
        EcMaterielElements eme = new EcMaterielElements();
        eme.setEcTemplateId(dbElement.getEcTemplateId());
        eme.setTemplateElementId(dbElement.getId());
        eme.setTemplateMaterielId(TemplateMaterielId);
        eme.setParentCode(e.getElementCategoryCode());
        eme.setElementCode(dbElement.getElementCode());
        eme.setElementContext(dbElement.getElementContext());
        eme.setMajor(e.getMajor());
        eme.setDescription(dbElement.getDescription());
        //add
        eme.setEcElementCategoryId(dbElement.getEcElementCategoryId());
        eme.setIsDelete(0);
        eme.setUserId(user.getTicket());
        eme.setOrgId(user.getOrgId());
        eme.setFillValue(e.getFillValue());


        //判断颜色是否修改
        changeElementColor(e, eme);
        return eme;
    }

    private EcTemplateMateriel getEcTemplateMateriel(EcTempMateSaveParam param, User user, EcTemplate ecTemplate, FeedWe weFeed) {

        EcTemplateMateriel s = new EcTemplateMateriel();

        //模板背景 如果模板存在 颜色背景在处理
        String templateBgStyle = null;
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(param.getMainBgColor())) {
            templateBgStyle = "1" + param.getMainBgColor();
            logger.info("getMainBackgroudColor isnot null templateId>>>" + param.getMainBgColor());
        }

        if (org.apache.commons.lang3.StringUtils.isNoneBlank(param.getJoinBgColor())) {
            templateBgStyle = "1" + param.getJoinBgColor();
            logger.info("getJoinBackgroudColor isnot null templateId>>>" + param.getJoinBgColor());
        }

        //重新生成EcTemplate完全编码 更换了颜色
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(templateBgStyle) && !templateBgStyle.equals(ecTemplate.getTemplateBgStyle())) {
            String templateName = ecTemplate.getTemplateName();
            String[] split = templateName.split("_");
            // 构造最新的全编码
            if (split.length > 5 && (split[4].equals("BG02") || split[4].equals("BG01"))
                    && split[5].startsWith("1") && org.apache.commons.lang3.StringUtils.isNoneBlank(ecTemplate.getTemplateBgStyle())) {
                split[5] = templateBgStyle;
                templateName = Joiner.on("_").join(split);
                ecTemplate.setTemplateBgStyle(templateBgStyle);
                logger.info("CreativeTemplateBuildServiceImpl 模板背景修改 templateName>>>" + ecTemplate.getTemplateName() + ";templateBgStyle>>>" + templateBgStyle + ";"
                        + ";newtemplateName>>>" + templateName);
                ecTemplate.setTemplateName(templateName);
            }
        }

        s.setTemplateCode(ecTemplate.getTemplateName());
        s.setFeedId(param.getFeedId());
        s.setTemplateId(param.getTemplateId());
        s.setTemplateContext(ecTemplate.getTemplateContext());
        s.setCreateTime(new Date());
        s.setOrgId(user.getOrgId());
        s.setUserId(user.getTicket());
        s.setName(param.getName());
        s.setCreatedStatus(0);  //默认
        s.setProductCount(weFeed.getProductCnt());
        s.setCreatedNum(0);
        s.setWidth(ecTemplate.getWidth());
        s.setHeight(ecTemplate.getHeight());
        return s;
    }

    @Override
    public Map findByEditOrCopy(String lang, Long id) {

        EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(id);
        Long feedId = ecTemplateMateriel.getFeedId();
        FeedWe feedWeById = feedRdbService.findFeedWeById(feedId);

        boolean isCn = true;
        if ("zh".equals(lang) || "zh-cn".equals(lang)) {
            isCn = true;
        } else {
            isCn = false;
        }

        List<EcMaterielElementsExt> ecMaterielElements = ecMaterielElementsRdbService.findExtByMaterielId(id);
        if (ecMaterielElements != null) {
            for (EcMaterielElementsExt ecMaterielElement : ecMaterielElements) {
                if (!isCn) {
                    ecMaterielElement.setName(ecMaterielElement.getUsName());
                }
            }
        }


        List<EcMaterielCategory> ecMaterielCategoryList = findEcMaterielCategory(id, isCn);

        Map<String, Object> map = new HashMap<>();
        map.put("productWeFeed", feedWeById);
        map.put("ecMaterielCategoryList", ecMaterielCategoryList);
        map.put("ecTemplateMateriel", ecTemplateMateriel);
        map.put("ecMaterielElements", ecMaterielElements);
        return map;
    }

    /**
     * 查找元素分类
     *
     * @param id
     * @param b
     * @return
     */
    private List<EcElementCategory> findEcElementCategoryList(Long id, boolean b) {
        List<EcElementCategory> result = new ArrayList<>();
        List<EcElementCategory> ecElementCategoryList = ecElementCategoryRdbService.findCnByMaterielId(id);
        for (EcElementCategory ecElementCategory : ecElementCategoryList) {
            Long id1 = ecElementCategory.getId();
            List<EcElementCategory> tmp = ecElementCategoryRdbService.findTopCategory(id1);
            if (tmp.size() > 1) {
                for (EcElementCategory elementCategory : tmp) {
                    if (elementCategory.getId().equals(id1)) {
                        continue;
                    } else {
                        elementCategory.getChildren().add(ecElementCategory);
                        result.add(ecElementCategory);
                    }
                }
            } else {
                EcElementCategory elementCategory = tmp.get(0);
                elementCategory.getChildren().add(ecElementCategory);
                result.add(ecElementCategory);
            }
        }
        return result;
    }

    /**
     * 组装模板样式分类
     *
     * @param id
     * @param isCn
     * @return
     */
    private List<EcMaterielCategory> findEcMaterielCategory(Long id, boolean isCn) {
        List<EcMaterielCategory> ecMaterielCategoryList = new ArrayList<>();

        List<EcMaterielCategory> temEcMaterielCategoryList = ecMaterielCategoryRdbService.findCnByMaterielId(id);
        //分组
        Map<Long, List<EcMaterielCategory>> group = new HashMap<>();
        for (EcMaterielCategory ecMaterielCategory : temEcMaterielCategoryList) {

            if (!isCn) {
                ecMaterielCategory.setCategoryName(ecMaterielCategory.getCategoryUsName());
            }
            Long pid = ecMaterielCategory.getPid();
            if (group.containsKey(pid)) {
                group.get(pid).add(ecMaterielCategory);
            } else {
                List<EcMaterielCategory> tempList = new ArrayList<>();
                tempList.add(ecMaterielCategory);
                group.put(pid, tempList);
            }
        }

        for (Map.Entry<Long, List<EcMaterielCategory>> longListEntry : group.entrySet()) {
            Long pid = longListEntry.getKey();
            List<EcMaterielCategory> value = longListEntry.getValue();
            EcMaterielCategory last = null;
            while (pid > 0) {
                EcMaterielCategory category = ecMaterielCategoryRdbService.findById(pid);
                if (!isCn) {
                    category.setCategoryName(category.getCategoryUsName());
                }
                if (last == null) {
                    category.setChildren(value);
                } else {
                    category.getChildren().add(last);
                }
                last = category;
                pid = category.getPid();
            }

            ecMaterielCategoryList.add(last);
        }
        return ecMaterielCategoryList;
    }

    @Override
    public boolean checkName(Long orgId, String name) {
        EcTemplateMateriel byNameAndOrgId = ecTemplateMaterielRdbService.findByNameAndOrgId(name, orgId);
        if (byNameAndOrgId != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<String> buildCreative(User user, EcBuildCreativeParam param) throws Exception {
        logger.info("CreativeTemplateBuildServiceImpl buildCreative begin.");

        Long ecTemplateMaterielId = param.getEcTemplateMaterielId();

        List<String> resultList = new ArrayList<>();
        //一、准备适用于该产品和feed的所有布局
        List<EcTemplate> ecTemplateList = buildFindEcTemplates(user, param);

        List<EcMaterielElements> srcDbElement = null;
        if (param.getEcTemplateMaterielId() != null && param.getEcTemplateMaterielId() > 0) {
            srcDbElement = ecMaterielElementsRdbService.findByMaterielId(ecTemplateMaterielId);
        }


        boolean isSuccess = false;
        CheckedException checkedException = null;

        if (ListUtil.isNotEmpty(ecTemplateList)) {
            for (EcTemplate ecTemplate : ecTemplateList) {

                logger.info("CreativeTemplateBuildServiceImpl 准备使用模板 templateId>>>" + ecTemplate.getId());

                //二、准备好前台 所选的主要元素和次要元素（包括填充值）
                List<EcMaterielElements> ecMaterielElementsList = new ArrayList<>();

                Long wefeedid = param.getWefeedid();
                for (TemplateElementVo templateElementVo : param.getElements()) {

                    boolean isFound = false;
                    if (srcDbElement != null) {  //判断是否
                        for (EcMaterielElements ecMaterielElements : srcDbElement) {
                            if (ecMaterielElements.getElementCode().equals(templateElementVo.getElementCode())) {
                                changeElementColor(templateElementVo, ecMaterielElements);
                                ecMaterielElementsList.add(ecMaterielElements);
                                isFound = true;
                            }
                        }

                    }

                    //假如前段重新更换 元素
                    if (!isFound) {
                        EcTemplateElement element = getEcTemplateElement(wefeedid, ecTemplate, templateElementVo);
                        if (element != null) {
                            EcMaterielElements eme = getEcMaterielElements(ecTemplateMaterielId, user, templateElementVo, element);
                            ecMaterielElementsList.add(eme);
                        } else {
                            logger.error("ecTemplateid >>>>" + ecTemplate.getId() + "模板没有找到对应的元素");
                            checkedException = new CheckedException(ResponseUtils.getMsg(ErrorType.NotFoundElement_ERROR));
                        }
                    }
                }
                if (ListUtil.isEmpty(ecMaterielElementsList) || ecMaterielElementsList.size() <= 1) {
                    logger.error("CreativeTemplateBuildServiceImpl buildCreative 模板{}未找到适用的元素.", ecTemplate.getId());
                    continue;
                }

                //替换模板背景颜色
                changeTempldateBgColor(ecTemplateMaterielId, ecTemplate, param.getMainBgColor(), param.getJoinBgColor());

                //三、从缓存中获取100张产品图
                List<Feed> feedList;
                if (param.getMore())
                    feedList = feedMongoService.sampleByFeed(wefeedid + "", 50);
                else
                    feedList = feedMongoService.sampleByFeed(wefeedid + "", 1);

                if (ListUtil.isNotEmpty(feedList)) {
                    isSuccess = true;
                    resultList.add(feedBuilderService.buildFeed(feedList, ecTemplate, ecMaterielElementsList));
                } else {
                    logger.error("wefeedid {} 未从缓存中获取到产品。", wefeedid);
                    checkedException =  new CheckedException(ResponseUtils.getMsg(ErrorType.NotFoundFeedInMongodb_ERROR));
                }
            }

            if (!isSuccess) { //没有成功
                throw checkedException;
            }
        } else {
            logger.info("没有找到对应的模板");
        }
        logger.info("CreativeTemplateBuildServiceImpl buildCreative end.");
        return resultList;
    }

    /**
     * 修改字体和元素背景颜色
     *
     * @param templateElementVo
     * @param ecMaterielElements
     */
    private void changeElementColor(TemplateElementVo templateElementVo, EcMaterielElements ecMaterielElements) {
        //判断颜色是否修改
        boolean isChangeColor = false;
        String templateElementVoBackgroundColor = templateElementVo.getBackgroundColor();
        String templateElementVoWordColor = templateElementVo.getWordColor();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(templateElementVoBackgroundColor)
                || org.apache.commons.lang3.StringUtils.isNoneBlank(templateElementVoWordColor)) {
            String context = ecMaterielElements.getElementContext();
            JSONObject contextJ = JSON.parseObject(context);
            String backgroundColor = contextJ.getString("backgroundColor");
            String color = contextJ.getString("color");

            //修改了背景
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(templateElementVoBackgroundColor)
                    && (backgroundColor == null || !backgroundColor.equals("#" + templateElementVoBackgroundColor))) {
                contextJ.put("backgroundColor", "#" + templateElementVoBackgroundColor);
                isChangeColor = true;
            }

            //修改了字体
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(templateElementVoWordColor)
                    && (color == null || !color.equals("#" + templateElementVoWordColor))) {
                contextJ.put("color", "#" + templateElementVoWordColor);
                isChangeColor = true;
            }

            if (isChangeColor) {
                String tempContext = contextJ.toJSONString();
                ecMaterielElements.setElementContext(tempContext);
            }
        }
    }

    private void changeTempldateBgColor(Long ecTemplateMaterielId, EcTemplate ecTemplate, String MainBackgroudColor, String JoinBackgroudColor) {
        //根据
        if (ecTemplateMaterielId != null && ecTemplateMaterielId > 0) {
            EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(ecTemplateMaterielId);
            String templateCode = ecTemplateMateriel.getTemplateCode();
            //没有更换模板
            if (ecTemplateMateriel.getTemplateId().equals(ecTemplate.getId())
                    && org.apache.commons.lang3.StringUtils.isNoneBlank(templateCode)
                    && (templateCode.contains("BG01") || templateCode.contains("BG02"))) {
                String[] split = templateCode.split("_");
                if (split.length > 5 && split[5].startsWith("1")) {
                    ecTemplate.setTemplateBgStyle(split[5].substring(1));
                }
            }
        }

        //如果颜色有修改
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(MainBackgroudColor)) {
            ecTemplate.setTemplateBgStyle("1" + MainBackgroudColor);
            logger.info("getMainBackgroudColor isnot null templateId>>>" + MainBackgroudColor);
        }

        if (org.apache.commons.lang3.StringUtils.isNoneBlank(JoinBackgroudColor)) {
            ecTemplate.setTemplateBgStyle("1" + JoinBackgroudColor);
            logger.info("getJoinBackgroudColor isnot null templateId>>>" + JoinBackgroudColor);
        }
    }

    private boolean isWordByElementCategory(String code) {
        EcElementCategory ecElementCategory = ecElementCategoryRdbService.findByCode(code);
        boolean isWord = false;
        if (null != ecElementCategory) {
            Integer p = ecElementCategory.getProperty();
            isWord = true;
            if (p == 0) {
                //固定
                isWord = false;
            }
        }
        return isWord;
    }

    @Override
    public Map<String, Object> buildAdvancedData(AdvancedParam param, Long orgId) {
        String primaryParentCode = param.getPrimaryElement().getParentCode();
        String auxiliaryParentCode = param.getAuxiliaryElement().getParentCode();
        //查询指定模板下、具体元素类型的元素s
        List<EcTemplateElementShowResult> mainElements = queryElements(param, primaryParentCode, orgId, true);
        List<EcTemplateElementShowResult> assistElements =
                queryElements(param, auxiliaryParentCode, orgId, false);
        Map<String, Object> results = new HashMap<>();
        if (!CollectionUtils.isEmpty(mainElements)) {
            boolean isWord = isWordByElementCategory(primaryParentCode);
            //按样式组分组
            Map<String, Map<String, Object>> styleGroups = buildStyleGroups(mainElements, isWord);
            //高级编辑获取默认元素
            EcTemplateElementShowResult defaultElement = defaultElement(param, param.getPrimaryElement(), isWord);
            Map<String, Object> primaryInfo = new HashMap<>();
            primaryInfo.put("styleGroups", styleGroups);
            primaryInfo.put("defaultElement", defaultElement);
            results.put("primary", primaryInfo);
        }

        if (!CollectionUtils.isEmpty(assistElements)) {
            boolean isWord = isWordByElementCategory(auxiliaryParentCode);
            //按样式组分组
            Map<String, Map<String, Object>> styleGroups = buildStyleGroups(assistElements, isWord);
            //高级编辑获取默认元素
            EcTemplateElementShowResult defaultElement = defaultElement(param, param.getAuxiliaryElement(), isWord);
            Map<String, Object> auxiliaryInfo = new HashMap<>();
            auxiliaryInfo.put("styleGroups", styleGroups);
            auxiliaryInfo.put("defaultElement", defaultElement);
            results.put("auxiliary", auxiliaryInfo);
        }

        //解析模板背景
        parseTemplateBg(param, results);

        return results;
    }

    private EcTemplateElementShowResult defaultElement(AdvancedParam param, TemplateElementVo element, boolean isWord) {
        if (null == param.getMaterialId() || null == element || null == element.getTemplateElementId()) {
            //如果不是复制编辑、或者替换了新元素，则无默认元素
            return null;
        }
        EcMaterielElements ecMaterielElements = ecMaterielElementsRdbService.findByMaterielIdAndElementIdAndParentCode(param.getMaterialId(), element.getTemplateElementId(), element.getParentCode());
        if (null == ecMaterielElements) {
            return null;
        }

        //确保当前模板与物料模板中的元素有关联关系
        EcTemplateElementShowResult defaultElement = null;
        if (StringUtils.isEquals("A01", element.getParentCode())) {
            //logo
            defaultElement = ecProductLogoRdbService.findByIdAndTemplateId(element.getTemplateElementId(), param.getTemplateId());
        } else {
            defaultElement = ecTemplateElementRdbService.findByIdAndTemplateId(element.getTemplateElementId(), param.getTemplateId());
        }

        if (null != defaultElement) {
            //将模板物料中的描述设置到默认元素中
            String context = ecMaterielElements.getElementContext();
            defaultElement.setElementContext(context);
            JSONObject contextJ = JSON.parseObject(context);
            defaultElement.setBackgroundColor(contextJ.getString("backgroundColor"));
            if (isWord) {
                defaultElement.setWordColor(contextJ.getString("color"));
            }
        }
        return defaultElement;
    }

    private void parseTemplateBg(AdvancedParam param, Map<String, Object> results) {
        if (null != param.getMaterialId()) {
            //如果传了materialId
            EcTemplateMateriel ecTemplateMateriel = ecTemplateMaterielRdbService.findEcTemplateMaterielById(param.getMaterialId());
            if (null != ecTemplateMateriel) {
                //则判断物料下的模板是否发生变更
                if (param.getTemplateId() == ecTemplateMateriel.getTemplateId()) {
                    //如果没有变更，则用物料下模板的背景颜色
                    parseTemplateBgColor(ecTemplateMateriel.getTemplateCode(), results);
                } else {
                    //如果发生变更，则使用最新的模板
                    EcTemplate ecTemplate = ecTemplateRdbService.findById(param.getTemplateId());
                    if (null != ecTemplate) {
                        parseTemplateBgColor(ecTemplate.getTemplateName(), results);
                    }
                }
            }
        } else {
            //未传物料Id，则解析当前模板的背景
            EcTemplate ecTemplate = ecTemplateRdbService.findById(param.getTemplateId());
            if (null != ecTemplate) {
                parseTemplateBgColor(ecTemplate.getTemplateName(), results);
            }
        }
    }

    private void parseTemplateBgColor(String templateCode, Map<String, Object> results) {
        if (StringUtils.isEmpty(templateCode)) {
            return;
        }
        String[] codes = templateCode.toUpperCase().split("_");
        if (codes.length < 6) {
            return;
        }
        //根据模板背景判断
        String templateBgType = codes[4];
        String templateBgStyle = codes[5];
        String bgColor;
        if (!StringUtils.isEmpty(templateBgStyle) && templateBgStyle.startsWith("1")) {
            //带颜色的背景类型
            bgColor = templateBgStyle.substring(1);
            if (StringUtils.isEquals(templateBgType, "BG01")) {
                //主体背景
                results.put("mainBgColor", bgColor);
            }

            if (StringUtils.isEquals(templateBgType, "BG02")) {
                //拼接背景
                results.put("joinBgColor", bgColor);
            }
        }
    }

    private Map<String, Map<String, Object>> buildStyleGroups(List<EcTemplateElementShowResult> mainElements, boolean isWord) {
        //按样式组排序
        Map<String, Map<String, Object>> styleGroups = new TreeMap<>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                //指定排序器按照降序排列
                return o1.compareTo(o2);
            }
        });

        String styleCode;
        //将查询当的元素按样式组进行分组
        for (EcTemplateElementShowResult element : mainElements) {
            //样式code
            styleCode = element.getStyleCode();
            Map<String, Object> styleGroupEs = styleGroups.get(styleCode);
            if (null == styleGroupEs) {
                styleGroupEs = new HashMap<>();
                styleGroups.put(styleCode, styleGroupEs);
                EcElementStyleColorTypeShowResult defaultColorType = EcElementStyleColorTypeRdbService.findByElementStyleId(element.getElementStyleGroupId());
                if (null != defaultColorType) {
                    styleGroupEs.put("defaultStyleColor", defaultColorType.getElementColorName());
                }

                styleGroupEs.put("elements", new ArrayList<EcTemplateElementShowResult>());
            }
            List<EcTemplateElementShowResult> elements = (List<EcTemplateElementShowResult>) styleGroupEs.get("elements");
            String defaultStyleColor = (String) styleGroupEs.get("defaultStyleColor");
            if (!StringUtils.isEmpty(defaultStyleColor) && StringUtils.isEquals(element.getElementColorName(), defaultStyleColor)) {
                styleGroupEs.put("hasDefaultColorElememt", true);
            }

            if (!StringUtils.isEmpty(element.getElementContext())) {
                String context = element.getElementContext();
                JSONObject contextJ = JSON.parseObject(context);
                element.setBackgroundColor(contextJ.getString("backgroundColor"));
                if (isWord) {
                    if(org.apache.commons.lang3.StringUtils.isNotEmpty(contextJ.getString("color"))){
                        element.setWordColor(contextJ.getString("color"));
                    } else  {
                        element.setWordColor(" ");
                    }
                }
            }
            elements.add(element);
        }

        //设置每个样式组的默认颜色，并且样式组下的元素按颜色排序
        for (Map.Entry<String, Map<String, Object>> styleGroupElements : styleGroups.entrySet()) {
            Map<String, Object> v = styleGroupElements.getValue();
            List<EcTemplateElementShowResult> elements = (List<EcTemplateElementShowResult>) v.get("elements");
            elements.sort((EcTemplateElementShowResult h1, EcTemplateElementShowResult h2) -> {
                if (h1.getElementColorTypeId() != null && h2.getElementColorTypeId() != null) {
                    return h1.getElementColorTypeId().compareTo(h2.getElementColorTypeId());
                } else {
                    return -1;
                }
            });
            Boolean hasDefaultColorElememt = (Boolean) v.get("hasDefaultColorElememt");
            if (null == hasDefaultColorElememt) {
                v.put("defaultStyleColor", elements.get(0).getElementColorName());
            }
        }

        return styleGroups;
    }

    private List<EcTemplateElementShowResult> queryElements(AdvancedParam param, String parentCode, Long orgId, boolean major) {
        if (StringUtils.isEquals("A01", parentCode)) {
            return ecProductLogoRdbService.findByFeedIdAndTemplateIdAndMajorAndOrgId(param.getWeFeedId(), param.getTemplateId(), major, orgId);
        } else {
            return ecTemplateElementRdbService.findByTemplateIdAndParentCodeAndMajorAndOrgId(param.getTemplateId(), parentCode, major, orgId);
        }
    }

    /**
     * build 查询模板
     *
     * @param user
     * @param param
     * @return
     */
    private List<EcTemplate> buildFindEcTemplates(User user, EcBuildCreativeParam param) {
        List<EcTemplate> ecTemplateList;//查看更多入口
        if (param.getMore()) {
            ecTemplateList = new ArrayList<>();
            ecTemplateList.add(ecTemplateRdbService.findById(param.getEcTemplateId()));
        } else {

            //update入口
            if (param.getEcTemplateId() != null && param.getEcTemplateId() > 0) {
                ecTemplateList = new ArrayList<>();
                ecTemplateList.add(ecTemplateRdbService.findById(param.getEcTemplateId()));
            }

            //新建入口 或者选择模板入口
            else {
                //处理options
                String options = param.getOptions();
                JSONObject jsonObject = JSONObject.parseObject(options);
                Set<String> strings = jsonObject.keySet();
                List<Long> ids = new ArrayList<>();
                for (String string : strings) {
                    JSONArray jsonArray = jsonObject.getJSONArray(string);
                    for (Object o1 : jsonArray) {
                        JSONObject el = (JSONObject) o1;
                        if (el.getBoolean("checked")) {
                            String categoryType = el.getString("categoryType");

                            Long id = el.getLong("id");
                            // 创意类型  // 展示位置  //创意结构（Carousel Ads） //创意结构（Link Ads）
                            if ("creativeType".equals(string)
                                    || "adPlaceMent".equals(string)
                                    || "adCarousel".equals(string)
                                    || "adLink".equals(string)) {
                                ids.add(id);
                            }
                        }
                    }
                }

                logger.info("查询条件user.getOrgId()>>>>" + user.getOrgId());
                logger.info("查询条件ids>>>>" + JSON.toJSONString(ids));
                ecTemplateList = ecTemplateRdbService.findByOrgIdAndCategory(user.getOrgId(), ids);
            }
        }
        return ecTemplateList;
    }

    @Override
    public void fixOriginalPicTempldate() {
        List<FeedWe> feedWes = feedRdbService.findAll();
        for (FeedWe feedWe : feedWes) {
            List<EcTemplateMateriel> materiels = ecTemplateMaterielRdbService.findByFeedId(feedWe.getId());

            boolean isFound = false;
            for (EcTemplateMateriel materiel : materiels) {
                // 空白模板
                if (materiel.getMaterielType() != null && materiel.getMaterielType() == 2) {
                    isFound = true;
                }
            }


            if (!isFound){
                feedBuilderService.initOriginalPicMateriel(feedWe);
            }
        }
    }
}
